package jt.classic.system.tablequery;

import jt.classic.system.ISystem;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserManager;
import jt.classic.system.utils.AnnexTool;

import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import org.limp.basework.Column;
import org.limp.basework.Table;
import org.limp.basework.impl.CommonBean4HSQ;

import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexInfo;

import java.sql.Connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class TableARGAction extends DispatchAction {
    /**
    * 查询项组件
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
    public ActionForward querycmp(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        if (ISystem.invalidSesstion(request)) {
            IUser user = UserManager.createGuestUser();

            ISystem.createSessionUser(request, user);
        }

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        param.put("sessionUserLogid", user.ilogid());
        param.put("sessionUserId", user.id());
        param.put("sessionUserName", user.iname());
        param.put("sessionGroupId", user.igroup().id());
        param.put("sessionGroupName", user.igroup().iname());
        param.put("sessionGroupNumber", user.igroup().inumber());

        String querykey = StringTool.checkString(param.get("querykey"));

        TableQuery tq = null;

        if (querykey.equals("")) {
            request.setAttribute("result",
                "{success: false, msg : '没有指定查询key,无法初始化查询项'}");
        } else {
            TableQueryCenter center = TableQueryCenter.getInstance();
            tq = center.getTableQuery(querykey);
        }

        if (tq == null) {
            request.setAttribute("result",
                "{success: false, msg : '通用查询设置无效,无法初始化查询项'}");
        } else if (tq.iresultItems() == null) {
            request.setAttribute("result",
                "{success: false, msg : '无查询项定义,无法初始化查询项'}");
        } else {
            List list = new ArrayList();

            List queryList = tq.iqueryItems();

            if ((queryList != null) && !queryList.isEmpty()) {
                for (int i = 0; i < queryList.size(); i++) {
                    Map item = (Map) queryList.get(i);

                    String paramValue = (String) item.get("param");

                    if (paramValue.startsWith("@")) {
                        paramValue = StringTool.checkString(param.get(
                                    paramValue.substring(1)));
                    }

                    TableQueryItemJsonBean bean = new TableQueryItemJsonBean();
                    bean.setName((String) item.get("label"));
                    bean.setColumn(((Column) item.get("column")).getName());
                    bean.setColumnName(((Column) item.get("column")).getDescription());
                    bean.setItemType(1);
                    bean.setNeed((String) item.get("need"));
                    bean.setMode((String) item.get("mode"));
                    bean.setPointId((String) item.get("pointId"));
                    bean.setPointName((String) item.get("pointName"));
                    bean.setParam(paramValue);
                    bean.setTable(((Column) item.get("column")).associateTable()
                                   .getName());
                    bean.setTableName(((Column) item.get("column")).associateTable()
                                       .getDescription());
                    bean.setType((String) item.get("type"));
                    bean.setColumnType(((Column) item.get("column")).getType()
                                        .toString());
                    bean.setTableHandleType("0");

                    list.add(bean);
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(list);

            String jsonString = "{success: true, \"queryCmp\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        }

        return mapping.findForward("jsonresult");
    }

    /**
    * 查询列表显示项组件
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
    public ActionForward modelcmp(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        if (ISystem.invalidSesstion(request)) {
            IUser user = UserManager.createGuestUser();

            ISystem.createSessionUser(request, user);
        }

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        param.put("sessionUserLogid", user.ilogid());
        param.put("sessionUserId", user.id());
        param.put("sessionUserName", user.iname());
        param.put("sessionGroupId",
            (user.igroup() != null) ? user.igroup().id() : "");
        param.put("sessionGroupName",
            (user.igroup() != null) ? user.igroup().iname() : "");
        param.put("sessionGroupNumber",
            (user.igroup() != null) ? user.igroup().inumber() : "");

        String querykey = StringTool.checkString(param.get("querykey"));

        /*默认组建类型*/
        String comptype = StringTool.checkString(param.get("comptype"));

        TableQuery tq = null;

        if (querykey.equals("")) {
            request.setAttribute("result",
                "{success: false, msg : '没有指定查询key,无法初始化系统对象数据列表'}");
        } else {
            TableQueryCenter center = TableQueryCenter.getInstance();
            tq = center.getTableQuery(querykey);
        }

        if (tq == null) {
            request.setAttribute("result",
                "{success: false, msg : '通用查询设置无效,无法初始化数据列表'}");
        } else if (tq.iresultItems() == null) {
            request.setAttribute("result",
                "{success: false, msg : '无列表显示项定义,无法初始化数据列表'}");
        } else {
            StringBuffer columnModleString = new StringBuffer(
                    "{'header': '<font class=\"oaFont\">序号</font>','dataIndex': 'PAGINATION_NUMBER','width':20, clazz : 'PAGINATION_NUMBER'}");

            StringBuffer fieldsNames = new StringBuffer(
                    "{name: 'PAGINATION_NUMBER'}");

            Table table = (Table) tq.itables().get(0);

            if (table.hasPrimaryKey()) {
                try {
                    Column column = table.column(table.getPrimaryKey()[0]);

                    fieldsNames.append(",{name: '" + column.getName() +
                        "', clazz : '" + column.getName() + "'}");
                } catch (Exception ex) {
                    ISystem.catchException(ex);
                }
            }

            List viewList = tq.iresultItems();

            if ((viewList != null) && !viewList.isEmpty()) {
                for (int i = 0; i < viewList.size(); i++) {
                    Map item = (Map) viewList.get(i);

                    if (!"-1".equals(item.get("show"))) {
                        columnModleString.append(
                            ",{'header': '<font class=\"oaFont\">" +
                            item.get("label") + "</font>','dataIndex': '" +
                            item.get("fieldName") +
                            "',sortable : true, clazz : '" + item.get("class") +
                            "', renderer: render" + comptype + "Header}");
                    }

                    fieldsNames.append(",{name: '" + item.get("fieldName") +
                        "'}");
                }
            }

            List list = new ArrayList();

            List queryList = tq.iqueryItems();

            if ((queryList != null) && !queryList.isEmpty()) {
                for (int i = 0; i < queryList.size(); i++) {
                    Map item = (Map) queryList.get(i);

                    String paramValue = (String) item.get("param");

                    if (paramValue.startsWith("@")) {
                        paramValue = StringTool.checkString(param.get(
                                    paramValue.substring(1)));
                    }

                    TableQueryItemJsonBean bean = new TableQueryItemJsonBean();
                    bean.setName((String) item.get("label"));
                    bean.setColumn(((Column) item.get("column")).getName());
                    bean.setColumnName(((Column) item.get("column")).getDescription());
                    bean.setItemType(1);
                    bean.setMode((String) item.get("mode"));
                    bean.setNeed((String) item.get("need"));
                    bean.setPointId((String) item.get("pointId"));
                    bean.setPointName((String) item.get("pointName"));
                    bean.setParam(paramValue);
                    bean.setTable(((Column) item.get("column")).associateTable()
                                   .getName());
                    bean.setTableName(((Column) item.get("column")).associateTable()
                                       .getDescription());
                    bean.setType((String) item.get("type"));
                    bean.setColumnType(((Column) item.get("column")).getType()
                                        .toString());
                    bean.setTableHandleType("0");

                    list.add(bean);
                }
            }

            JSONArray jsonArray = JSONArray.fromObject(list);

            request.setAttribute("result",
                "{success: true, title: '" + tq.iname() + "', js:'" +
                tq.ijsurl() + "', css:'" + tq.icssurl() + "', showchk : '" +
                tq.ishowchk() + "', defaultlist : '" + tq.idefaultlist() +
                "', exportlist : '" + tq.iexport() +
                "', columModel: [" +
                columnModleString.toString() + "], fieldsNames : [" +
                fieldsNames.toString() + "], queryCmp: " +
                jsonArray.toString() + "}");
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 执行对象实例查询操作
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        if (ISystem.invalidSesstion(request)) {
            IUser user = UserManager.createGuestUser();

            ISystem.createSessionUser(request, user);
        }

        IUser user = ISystem.getSessionUser(request);

        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String pageNO = StringTool.checkString(param.get("pageNO"));

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        String querykey = StringTool.checkString(param.get("querykey"));

        String orderby = StringTool.checkString(param.get("orderby"));

        String orderbykey = StringTool.checkString(param.get("orderbykey"));

        String queryAction = StringTool.checkString(param.get("queryAction"));

        param.put("sessionUserLogid", user.ilogid());
        param.put("sessionUserId", user.id());
        param.put("sessionUserName", user.iname());
        param.put("sessionGroupId",
            (user.igroup() != null) ? user.igroup().id() : "");
        param.put("sessionGroupName",
            (user.igroup() != null) ? user.igroup().iname() : "");
        param.put("sessionGroupNumber",
            (user.igroup() != null) ? user.igroup().inumber() : "");

        TableQuery tq = null;

        if (querykey.equals("")) {
            request.setAttribute("result",
                "{success: false, msg : '没有指定查询key,无法初始化系统对象数据列表'}");
        } else {
            TableQueryCenter center = TableQueryCenter.getInstance();
            tq = center.getTableQuery(querykey);
        }

        if (tq == null) {
            request.setAttribute("result",
                "{success: false, msg : '通用查询设置无效,无法初始化数据列表'}");
        } else if (tq.iresultItems() == null) {
            request.setAttribute("result",
                "{success: false, msg : '无列表显示项定义,无法初始化数据列表'}");
        } else {
            String orderbyTableName = orderbykey.equals("") ? ""
                                                            : orderbykey.substring(0,
                    orderbykey.indexOf("."));

            String orderbyColumnName = orderbykey.equals("") ? ""
                                                             : orderbykey.substring(orderbykey.indexOf(
                        ".") + 1);

            String sql = null;

            /*首次加载列表并且列表默认不显示列表数据*/
            if (queryAction.equals("") && !tq.idefaultlist()) {
                List tables = tq.itables();

                Table table = (Table) tables.get(0);

                sql = "SELECT ";

                if (table.hasPrimaryKey()) {
                    try {
                        Column column = table.column(table.getPrimaryKey()[0]);

                        sql += column.getName();
                    } catch (Exception ex) {
                        ISystem.catchException(ex);
                    }
                }

                sql += (" FROM " + table.getName() + " WHERE 1 = -1");
            } else {
                sql = TableARGTool.getListSQL4Query(user, tq, param);
            }

            request.setAttribute("orderby", orderby);

            request.setAttribute("orderbykey", orderbykey);

            request.setAttribute("query", param);

            String sql1 = "SELECT COUNT(*) FROM (" + sql + ") TAB";

            String sql2 = sql;

            List orderbyList = tq.iorderbyItems();

            /*动态排序设置*/
            if (!orderbykey.equals("")) {
                sql2 += (" ORDER BY " + orderbyColumnName + " " + orderby);
            } else if ((orderbyList != null) && !orderbyList.isEmpty()) {
                /*查询定义中存在排序定义*/
                for (int i = 0; i < orderbyList.size(); i++) {
                    Map temp = (Map) orderbyList.get(i);

                    String columnName = ((Column) temp.get("column")).getName();
                    String mode = (String) temp.get("mode");

                    if (i == 0) {
                        sql2 += (" ORDER BY " + columnName + " " + mode);
                    } else {
                        sql2 += (", " + columnName + " " + mode);
                    }
                }
            }

            String url = jt.classic.system.ISystem.getContextPath() +
                "/system/tablearg.do?querykey=" + querykey;

            try {
                SystemDataSource ds = SystemDataSource.getInstance();
                conn = ds.getConnection();

                QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

                // 设置
                plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
                plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
                plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
                plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
                plus.setParameter(QueryJackFactory.PAGINATION_COUNT, size);
                plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

                // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
                List resultList = plus.work();

                Table table = (Table) tq.itables().get(0);

                List resultAnnexItems = tq.iresultAnnexItems();

                /*显示项存在附件类型并且表存在主键*/
                if ((resultAnnexItems != null) && !resultAnnexItems.isEmpty() &&
                        table.hasPrimaryKey()) {
                    AnnexTool annexTool = new AnnexTool(conn);

                    String keyColumnName = table.getPrimaryKey()[0];

                    for (int j = 0; j < resultList.size(); j++) {
                        Map info = (Map) resultList.get(j);

                        String id = (String) info.get(keyColumnName);

                        for (int i = 0; i < resultAnnexItems.size(); i++) {
                            Map temp = (Map) resultAnnexItems.get(i);
                            Column column = (Column) temp.get("column");

                            AnnexInfo[] annexs = annexTool.getAnnexs(id,
                                    table.getName());

                            if ((annexs != null) && (annexs.length > 0)) {
                                List annexList = new ArrayList();

                                for (int kk = 0; kk < annexs.length; kk++) {
                                    AnnexInfo ai = annexs[kk];
                                    Map annexInfo = new HashMap();
                                    annexInfo.put("id", ai.getID());
                                    annexInfo.put("name", ai.getName());
                                    annexInfo.put("type", ai.getType());
                                    annexInfo.put("folder", ai.getRepository());
                                    annexInfo.put("url", ai.getLinkString());
                                    annexList.add(annexInfo);
                                }

                                info.put(column.getName(), annexList);
                            }
                        }
                    }
                }

                // 显示标签
                Label label = plus.getLabel();

                JSONArray jsonArray = JSONArray.fromObject(resultList);

                String jsonString = "{\"pageNO\":\"" + label.current() +
                    "\",\"totalPage\":\"" + label.totalfan() +
                    "\",\"totalCount\":\"" + label.totaldata() +
                    "\",\"queryList\":";
                jsonString += jsonArray.toString();
                jsonString += "}";

                request.setAttribute("result", jsonString);
            } catch (Exception ex) {
                request.setAttribute("result", "{success: false}");
                ISystem.catchException(request, this, ex);
            } finally {
                SystemDataSource.closeConnection(conn);
            }
        }

        return mapping.findForward("jsonresult");
    }
}
